<template>
  <div style="padding: 10px 0px; background-color: white">
    <van-form @submit="submitForm">
      <searchable-picker
        v-if="isRenewal === '1'"
        @change="paddingOrderData"
        v-model="form.parentOrderId"
        :columns="parentOrderList"
        valueKey="orderId"
        labelKey="orderName"
        label="原商机"
        placeholder="请选择原商机"
        :rules="[{ required: true, message: '请选择原商机' }]"
      />
      <searchable-picker
        v-model="form.customerId"
        :columns="customerList"
        valueKey="customerId"
        labelKey="customerName"
        label="客户名称"
        placeholder="点击选择客户名称"
        :rules="[{ required: true, message: '请选择客户名称' }]"
      />
      <van-field
        v-model="form.orderName"
        label="商机名称"
        placeholder="请输入商机名称"
        :rules="[{ required: true, message: '请输入商机名称' }]"
      />
      <searchable-picker
        v-model="form.orderAscription"
        :columns="getGroupData()"
        valueKey="value"
        labelKey="label"
        label="商机归属"
        placeholder="请选择商机归属"
        :rules="[{ required: true, message: '请选择商机归属' }]"
      />
      <van-collapse v-model="activeNames" class="product">
        <van-collapse-item title="产品明细" name="1">
          <searchable-picker
            v-model="form.productId"
            :columns="productList"
            valueKey="productId"
            labelKey="productName"
            label="产品名称"
            placeholder="点击选择产品名称"
            :rules="[{ required: true, message: '请选择产品名称' }]"
          />
          <van-field name="radio" label="单选框">
            <template #input>
              <van-radio-group
                v-model="form.isDiscount"
                direction="horizontal"
                @change="isDiscountChange"
              >
                <van-radio name="0">申请折扣</van-radio>
                <van-radio name="1">不申请折扣</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            readonly
            v-model="form.marketPrice"
            label="产品市场价格"
            type="number"
            placeholder="选择产品后自动填充"
          />
          <van-field
            :readonly="form.isDiscount === '1'"
            v-model="form.crmOrderProductDiscount.discountPrice"
            label="产品出货价格"
            type="number"
            placeholder="请输入产品申请折扣后的价格"
            :rules="[{ required: true, message: '请输入产品申请折扣后的价格' }]"
          />
          <van-field
            readonly
            v-model="form.discountRate"
            label="折扣率"
            placeholder="输入产品出货价格后自动填充"
            v-if="form.isDiscount === '0'"
          />
          <van-field
            v-model="form.crmOrderProductDiscount.remark"
            rows="3"
            autosize
            label="申请备注"
            type="textarea"
            placeholder="请输入申请备注"
            v-if="form.isDiscount === '0'"
            :rules="[{ required: true, message: '请输入申请备注' }]"
          />
        </van-collapse-item>
      </van-collapse>

      <!-- <van-field
        v-model="form.amount"
        type="number"
        label="商机金额"
        placeholder="请输入商机金额"
        :rules="[{ required: true, message: '请输入商机金额' }]"
      /> -->
      <van-field
        v-model="form.budget"
        type="number"
        label="商机预算"
        placeholder="请输入商机预算"
        :rules="[{ required: true, message: '请输入商机预算' }]"
      />
      <searchable-picker
        v-model="form.progess"
        :columns="dict.type.project_progress"
        valueKey="value"
        labelKey="label"
        label="项目进度"
        placeholder="请选择项目进度"
        :rules="[{ required: true, message: '请选择项目进度' }]"
        :readonly="form.orderId !== '-1'"
      />
      <van-field
        v-model="form.planPurchaseTime"
        :label="`${isRenewal === '0' ? '下单' : '续费'}时间`"
        placeholder="请选择预计下单时间"
        @click="planPurchaseTimeFlag = true"
        :rules="[{ required: true, message: '请选择下单时间' }]"
      />
      <van-calendar
        v-model="planPurchaseTimeFlag"
        @confirm="onConfirm($event, 'planPurchaseTimeFlag', 'planPurchaseTime')"
      />
      <van-field
        v-model="form.planAmount"
        type="number"
        :label="`${isRenewal === '0' ? '项目' : '续费'}金额`"
        placeholder="请输入预计项目金额"
        :rules="[{ required: true, message: '请输入项目金额' }]"
      />
      <van-field
        v-if="isRenewal === '1'"
        v-model="form.renewalEndTime"
        label="续费到期时间"
        placeholder="请选择续费到期时间"
        @click="renewalEndTimeFlag = true"
      />
      <van-calendar
        v-model="renewalEndTimeFlag"
        @confirm="onConfirm($event, 'renewalEndTimeFlag', 'renewalEndTime')"
      />
      <van-field
        v-model="form.contactPerson"
        label="客户联系人"
        placeholder="请输入客户联系人"
      />
      <van-field
        v-model="form.clientPhone"
        label="客户联系电话"
        placeholder="请输入客户联系电话"
      />
      <van-field
        v-model="form.cooperater"
        label="集成商"
        placeholder="请输入集成商"
      />
      <van-field
        v-model="form.cooperaterPerson"
        label="集成商联系人"
        placeholder="请输入集成商联系人"
      />
      <van-field
        v-model="form.cooperaterPhone"
        label="集成商电话"
        placeholder="请输入集成商联系电话"
      />
      <searchable-picker
        v-model="form.helpPerson"
        multiSelect
        :columns="userList"
        valueKey="userId"
        labelKey="userName"
        label="协同人"
        placeholder="请选择协同人"
      />
      <van-field
        v-model="form.plan"
        rows="3"
        autosize
        label="项目计划"
        type="textarea"
        placeholder="请输入内容"
      />
      <van-field
        v-model="form.contactContent"
        rows="3"
        autosize
        label="沟通情况"
        type="textarea"
        placeholder="请输入沟通情况"
      />
      <van-field
        style="margin-bottom: 50px"
        v-model="form.remark"
        rows="3"
        autosize
        label="备注"
        type="textarea"
        placeholder="请输入备注"
      />
      <div class="mobile-footer">
        <van-button
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="status = '0'"
          >暂存</van-button
        >
        <van-button
          type="info"
          native-type="submit"
          style="width: 49%; border-radius: 10px"
          @click="status = '1'"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { getOrder, addOrder, updateOrder, getOrderOne, getCrmOrderAllNoPage } from "@/api/crm/order";

import { getUserListByStatus } from "@/api/system/user";

import { getCrmCustomerAllNoPage } from "@/api/crm/customer";

import { getProductListNoPage } from "@/api/crm/product";
export default {
  name: "OrderAdd",
  dicts: ["project_type", "project_progress"],
  props: {
    isRenewal: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      activeNames: ["1"],
      product: {},
      // 表单参数
      form: {
        shippingPrice: 0,
        productId: "",
        isDiscount: "0",
        marketPrice: 0,
        crmOrderProductDiscount: {},
      },
      parentOrderList: [],
      buttonFlag: false,
      title: "新增",
      planPurchaseTimeFlag: false,
      renewalEndTimeFlag: false,
      userList: [],
      productList: [],
      customerList: [],
      orderId: "",
      status: "0",
    };
  },
  watch: {
    "form.crmOrderProductDiscount.discountPrice": {
      handler(val) {
        this.form.discountRate = (
          ((parseFloat(this.form.crmOrderProductDiscount.discountPrice) || 0) /
            (parseFloat(this.form.marketPrice) || 1)) *
          100
        ).toFixed(2);
      },
      deep: true,
    },
    "form.productId": {
      deep: true,
      handler(val) {
        if (val) {
          this.product = this.productList.find(
            (item) => item.productId === val
          );
          this.form.marketPrice = this.product.marketPrice;
        }
      },
    },
  },
  async created() {
    this.orderId = this.$route.params.orderId;
    await this.getProductListNoPage();
    await this.getUserListByStatus();
    await this.getCrmCustomerAllNoPage();
    if(this.isRenewal === '1'){
      await this.getCrmOrderAllNoPage();
    }
    await this.handleUpdate();

   
  },
  methods: {
    paddingOrderData(orderId) {
      if(!orderId || typeof orderId !== "string") return
      console.log(orderId, "sdadsadsa")
      let obj = this.parentOrderList.find((item) => item.orderId === orderId);

      if(!obj) return

      this.form.customerId = obj.customerId;
      this.form.orderName = obj.orderName + "_续费_" + new Date().getFullYear();
      this.form.amount = obj.amount;

      this.$set(this.form, "productId", obj.productId)

      this.product = this.productList.find((item) => item.productId === this.form.productId);
      this.$set(this.form, "marketPrice", this.product.marketPrice)

      this.form.isDiscount = '1'
      this.form.budget = obj.budget;
      this.form.contactPerson = obj.contactPerson;
      this.form.clientPhone = obj.clientPhone;
      this.form.cooperater = obj.cooperater;
      this.form.cooperaterPerson = obj.cooperaterPerson;
      this.form.cooperaterPhone = obj.cooperaterPhone;
      this.form.helpPerson = obj.helpPerson ? obj.helpPerson.split(",") : null;
      this.form.plan = obj.plan;
      this.form.contactContent = obj.contactContent;
      this.form.remark = obj.remark;

      console.log(this.form)
    },
    getCrmOrderAllNoPage() {
      getCrmOrderAllNoPage({ orderType: "0" }).then((res) => {
        this.parentOrderList = res.data;
      });
    },
    isDiscountChange(val) {
      if (val === "1") {
        this.$set(
          this.form.crmOrderProductDiscount,
          "discountPrice",
          this.product.shippingPrice
        );
      } else {
        this.$set(this.form.crmOrderProductDiscount, "discountPrice", null);
      }
    },
    getProductListNoPage() {
      getProductListNoPage({}).then((res) => {
        this.productList = res.data;
      });
    },
    getUserListByStatus() {
      getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },
    getCrmCustomerAllNoPage() {
      getCrmCustomerAllNoPage({}).then((res) => {
        this.customerList = res.data;
      });
    },
    // 日历回调
    onConfirm(date, flag, fildes) {
      this[flag] = false;
      this.form[fildes] = `${date.getFullYear()}-${
        date.getMonth() + 1
      }-${date.getDate()}`;
    },
    reset() {
      this.form = {
        orderId: null,
        orderName: null,
        customerId: null,
        amount: null,
        helpPerson: null,
        contactContent: null,
        budget: null,
        progess: null,
        contactPerson: null,
        clientPhone: null,
        cooperater: null,
        cooperaterPerson: null,
        cooperaterPhone: null,
        plan: null,
        nextFollowupTime: null,
        planPurchaseTime: null,
        status: null,
        planAmount: null,
        renewalTime: null,
        renewalAmount: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null,
        crmOrderProductDiscount: {},
        isDiscount: "0",
      };
    },
    handleUpdate() {
      this.reset();
      this.form.orderId = this.$route.params.orderId;
      if (this.form.orderId !== "-1") {
        getOrder(this.form.orderId).then((response) => {
          this.form = response.data;
          if (this.form.helpPerson) {
            this.form.helpPerson = this.form.helpPerson.split(",");
          }
          this.title = "修改";
        });
      } else {
        getOrderOne({ status: "0", orderType: this.isRenewal }).then((res) => {
          if (res.data) {
            this.form = res.data
            if (this.form.helpPerson) {
              this.form.helpPerson = this.form.helpPerson.split(",");
             
            }
            this.product = this.productList.find(
              (item) =>
                item.productId === this.form.crmOrderProductDiscount.productId
            );
            this.form.marketPrice = this.product.marketPrice;
          }
        });
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.form.status = this.status;
      this.form.helpPerson = this.form.helpPerson?.join(",");
      this.form.crmOrderProductDiscount.productId = this.form.productId;
      this.form.orderType = this.isRenewal;
      if (this.form.orderId !== "-1") {
        updateOrder(this.form).then((response) => {
          this.$toast.success("修改成功");
          if(this.isRenewal === '0') {
              this.$router.replace("/crm/order");
          } else {
            this.$router.replace("/crm/renewal");
          }
        });
      } else {
        addOrder(this.form).then((response) => {
          this.$toast.success("添加成功");
          if(this.isRenewal === '0') {
              this.$router.replace("/crm/order");
          } else {
            this.$router.replace("/crm/renewal");
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.submitButton {
  width: 95%;
  height: 50px;
  position: fixed;
  top: 90%;
  left: 10px;
}

::v-deep .van-collapse-item__content {
  padding: 0;
}

::v-deep .product .van-collapse-item__title {
  background-color: #eceff2;
  padding: 5px 16px;
}
</style>